var express = require('express');
var router = express.Router();
var mongo = require("./db")
// 为了处理mongodb的_id 的问题
var mongodb = require("mongodb")
var ObjectId = mongodb.ObjectId;

/* GET home page. */
router.get('/', function (req, res, next) {
  // res.render('index', { title: 'Express' });
});
// 获取价格排序数据的接口
router.post("/orderData", function (req, res) {
  if (req.body.orderPrice == "nosort") {
    mongo("find", "babylist", {}, function (data) {
      res.send(data)
    })
  } else {
    mongo("sorts", "babylist", {}, function (data) {  //通过价格排序
      res.send(data)
    }, { price: Number(req.body.orderPrice) })  //1  -1  
  }
})




// 添加接口
router.post("/add", function (req, res) {
  // 添加接口 整理前端传来的所有数据 添加到数据库
  var obj = {
    pname: req.body.pname,
    img: req.body.img,
    price: req.body.price,
    sel: req.body.sel
  }
  mongo("insert", "babylist", obj, function () {
    res.send({ success: "添加成功" })
  })
})

// 查询所有商品接口
router.post("/all", function (req, res) {
  // 查询所有数据返回给前端
  var sel = {}
  if (req.body.price) {
    sel.price = req.body.price
  }
  if (req.body.sel) {
    sel.sel = req.body.sel
  }
  console.log(req.body.pname)
  if (req.body.pname) {
    sel.pname = req.body.pname
  }
  mongo("find", "babylist", sel, function (data) {
    res.send(data)
  })
})

// 删除接口
router.post("/del", function (req, res) {
  //                          用ObjectId 去包裹前端传来的id
  mongo("del", "babylist", { _id: ObjectId(req.body.id) }, function (result) {
    if (result.n == 1) {
      res.send({ success: "删除成功" })
    } else {
      res.send({ err: "预期之外的错误" })
    }
  })
})
//点击修改 获取修改的当前行数据
router.post("/findData", function (req, res) {
  mongo("find", "babylist", { _id: ObjectId(req.body.id) }, function (data) {
    console.log(data)
    res.send(data[0])//返回当前要修改的数据行
  })
})
//  修改接口
router.post("/update", function (req, res) {
  // 准备好新的数据 通过id 更新原来的数据
  var obj = {
    pname: req.body.pname,
    img: req.body.img,
    price: req.body.price,
    sel: req.body.sel
  }
  // 数据库的更新操作
  mongo("update", "babylist", [{ _id: ObjectId(req.body.id) }, obj], function () {
    res.send({ success: "修改成功" })
  })
})
// 上移下移  
router.post("/upAndDown", function (req, res) {
  // 前端传来id 

  mongo("find", "babylist", {}, function (data) {
    var temp;
    // 查询到所有数据

    for (var i = 0; i < data.length; i++) {
      if (ObjectId(req.body.id) == data[i]._id) {
        temp = data[i]
        console.log(req.body.status)
        if (req.body.status == "down") {
          console.log(888888888)
          data[i] = data[i + 1]
          data[i + 1] = temp;
        } else if (req.body.status == "up") {
          data[i] = data[i - 1]
          data[i - 1] = temp;
        }
        break;
      }
    }
    res.send(data)
  })
})


module.exports = router;
